import 'package:dio/dio.dart';
import 'package:flutter_application_pd/common/index.dart';

class Api {
  static final Api _singleton = Api._init();
  static late Dio _dio;

  static Api get instance => _singleton;

  Api._init() {
    _dio = Dio(BaseOptions(
      baseUrl: 'http://jctt.net/yonghu',
      // connectTimeout: 5000,
      // receiveTimeout: 3000,
    ));

    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          print('请求之前');
          print(options.headers);
          print(options.path);
          List<String> whiteList = [
            '/login/login',
            '/register',
            '/login/houqugonggao'
          ];
          if (whiteList.contains(options.path)) {
            return handler.next(options);
          } else {
            var store = await Store.getInstance();
            var token = store?.get('token');
            print('token$token');
            options.headers["token"] = token;
          }
          print(options.headers);
          return handler.next(options); //continue
          // If you want to resolve the request with some custom data，
          // you can resolve a `Response` object eg: `handler.resolve(response)`.
        },
      ),
    );
  }

  Future<Response> get(String url, {Map<String, dynamic>? parameters}) async {
    try {
      var response = await _dio.get(url, queryParameters: parameters);
      return response;
    } catch (e) {
      throw Exception(e);
    }
  }

  Future<Response> post(String url, {Map<String, dynamic>? data}) async {
    try {
      var response = await _dio.post(url, data: data);
      return response;
    } catch (e) {
      throw Exception(e);
    }
  }

  // 文件上传
  Future<Response> uploadFile(String urlPath, String filePath) async {
    var name =
        filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
    var file = await MultipartFile.fromFile(filePath, filename: name);
    var formData = FormData.fromMap({"daoru": file});

    return await _dio.post(urlPath, data: formData);
  }

  // 文件下载
  Future<void> downloadFile(String urlPath, String savePath) async {
    await _dio.download(urlPath, savePath);
  }
}
